<template>
  <div class="quality-inspection-page">
    <div class="breadcrumb-container">
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-nav">
        <el-breadcrumb-item :to="{ path: '/' }" class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><HomeFilled /></el-icon>
          <span>主页</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><Setting /></el-icon>
          <span>质检管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item active">
          <el-icon class="breadcrumb-icon"><Histogram /></el-icon>
          <span>报工检验记录</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" class="filter-form" inline @keyup.enter="handleSearch">
        <el-form-item>
          <el-input v-model="searchForm.reportKeyword" placeholder="请输入检验单名称/号" clearable />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.orderKeyword" placeholder="请输入工单名称/编号" clearable />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.inspector"
            placeholder="请选择检验人员"
            clearable
            class="w-180"
          >
            <el-option
              v-for="option in inspectorOptions"
              :key="option"
              :label="option"
              :value="option"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            class="w-180"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <div class="filter-actions">
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-dropdown trigger="click">
            <el-button class="more-btn">
              更多
              <el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="ElMessage.info('示例：导出检验报表')">
                  导出报表
                </el-dropdown-item>
                <el-dropdown-item @click="ElMessage.info('示例：列设置')">
                  列设置
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <div class="toolbar">
        <el-button type="primary" @click="handleAction('新增')">新增</el-button>
        <el-button type="warning" plain @click="handleAction('导入')">导入</el-button>
      </div>

      <el-table
        :data="rows"
        border
        stripe
        :loading="loading"
        height="640"
        class="inspection-table"
        @selection-change="onSelectionChange"
      >
        <el-table-column type="selection" width="48" fixed="left" />
        <el-table-column type="index" label="序号" width="70" align="center" fixed="left" />
        <el-table-column prop="inspectionName" label="检验单名称" min-width="160" fixed="left" show-overflow-tooltip />
        <el-table-column prop="inspectionCode" label="检验单号" min-width="150" fixed="left" />

        <el-table-column prop="orderName" label="工单名称" min-width="150" />
        <el-table-column prop="taskName" label="任务名称" min-width="150" />
        <el-table-column prop="siteName" label="站点名称" min-width="140" />
        <el-table-column prop="processName" label="工序名称" min-width="140" />
        <el-table-column prop="productName" label="产品名称" min-width="160" />
        <el-table-column prop="productCode" label="产品编号" min-width="140" />
        <el-table-column prop="teamName" label="班组名称" min-width="140" />
        <el-table-column prop="taskOwner" label="任务负责人" min-width="140" />
        <el-table-column prop="reportUser" label="报工人员" min-width="140" />
        <el-table-column prop="reportQty" label="报工数量" min-width="120" />
        <el-table-column prop="reportTime" label="报工时间" min-width="160" />
        <el-table-column prop="inspectionTime" label="检验时间" min-width="160" />
        <el-table-column prop="inspectionType" label="检验类型" min-width="140" />
        <el-table-column prop="inspectionDept" label="检验部门" min-width="140" />
        <el-table-column prop="inspector" label="检验人" min-width="120" />
        <el-table-column prop="checkQty" label="检测数量" min-width="120" />
        <el-table-column prop="qualifiedQty" label="合格数量" min-width="120" />
        <el-table-column prop="unqualifiedQty" label="不合格数量" min-width="120" />
        <el-table-column prop="qualifiedRate" label="合格率" min-width="120" />
        <el-table-column prop="result" label="检测结果" min-width="130" />

        <el-table-column label="状态" width="120" fixed="right" align="center">
          <template #default="scope">
            <el-tag :type="statusTag(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleRowAction('查看', scope.row)">查看</el-button>
            <el-divider direction="vertical" />
            <el-button type="danger" link @click="handleRowAction('删除', scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="mt-12 flex-end">
        <el-pagination
          v-model:current-page="pager.page"
          v-model:page-size="pager.size"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pager.total"
          @size-change="onPageSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ArrowDown, ArrowRight, Histogram, HomeFilled, Setting } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'

interface InspectionItem {
  id: number
  inspectionName: string
  inspectionCode: string
  orderName: string
  taskName: string
  siteName: string
  processName: string
  productName: string
  productCode: string
  teamName: string
  taskOwner: string
  reportUser: string
  reportQty: number
  reportTime: string
  inspectionTime: string
  inspectionType: string
  inspectionDept: string
  inspector: string
  checkQty: number
  qualifiedQty: number
  unqualifiedQty: number
  qualifiedRate: string
  result: string
  status: string
}

const loading = ref(false)
const allRows = ref<InspectionItem[]>(generateMockInspections())
const rows = ref<InspectionItem[]>([])
const multipleSelection = ref<InspectionItem[]>([])

const pager = reactive({
  page: 1,
  size: 10,
  total: 0
})

const searchForm = reactive({
  reportKeyword: '',
  orderKeyword: '',
  inspector: '',
  status: ''
})

const statusOptions = [
  { label: '待检验', value: '待检验' },
  { label: '检验中', value: '检验中' },
  { label: '已完成', value: '已完成' },
  { label: '已关闭', value: '已关闭' }
]

const inspectorOptions = computed(() => {
  const set = new Set(allRows.value.map(item => item.inspector))
  return Array.from(set)
})

const fetchList = () => {
  loading.value = true
  setTimeout(() => {
    applyFilters()
    loading.value = false
  }, 300)
}

const applyFilters = () => {
  let data = [...allRows.value]

  if (searchForm.reportKeyword.trim()) {
    const keyword = searchForm.reportKeyword.trim()
    data = data.filter(
      item => item.inspectionName.includes(keyword) || item.inspectionCode.includes(keyword)
    )
  }

  if (searchForm.orderKeyword.trim()) {
    const keyword = searchForm.orderKeyword.trim()
    data = data.filter(
      item => item.orderName.includes(keyword) || item.taskName.includes(keyword)
    )
  }

  if (searchForm.inspector) {
    data = data.filter(item => item.inspector === searchForm.inspector)
  }

  if (searchForm.status) {
    data = data.filter(item => item.status === searchForm.status)
  }

  pager.total = data.length
  const start = (pager.page - 1) * pager.size
  rows.value = data.slice(start, start + pager.size)
}

const handleSearch = () => {
  pager.page = 1
  applyFilters()
}

const handleReset = () => {
  searchForm.reportKeyword = ''
  searchForm.orderKeyword = ''
  searchForm.inspector = ''
  searchForm.status = ''
  pager.page = 1
  applyFilters()
}

const onSelectionChange = (val: InspectionItem[]) => {
  multipleSelection.value = val
}

const onPageSizeChange = (size: number) => {
  pager.size = size
  pager.page = 1
  applyFilters()
}

const onPageChange = (page: number) => {
  pager.page = page
  applyFilters()
}

const handleAction = (action: string) => {
  ElMessage.info(`${action}操作示例`)
}

const handleRowAction = (action: string, row: InspectionItem) => {
  if (action === '删除') {
    ElMessage.warning(`删除检验单：${row.inspectionCode}`)
  } else {
    ElMessage.info(`查看检验单：${row.inspectionCode}`)
  }
}

const statusTag = (status: string) => {
  switch (status) {
    case '检验中':
      return 'warning'
    case '待检验':
      return 'info'
    case '已关闭':
      return 'danger'
    case '已完成':
      return 'success'
    default:
      return ''
  }
}

type MockInspector = string

function generateMockInspections(): InspectionItem[] {
  const statuses = ['待检验', '检验中', '已完成', '已关闭']
  const inspectors: MockInspector[] = ['刘勇', '朱军', '陈倩', '赵敏']
  const ownerPool = ['刘主任', '李主管', '王班长']
  const reporterPool = ['赵组长', '孙操作', '周检验']

  const inspectionTypePool = ['首检', '巡检', '终检']

  return Array.from({ length: 20 }).map((_, idx) => {
    const plan = 50 + idx * 3
    const checkQty = plan - (idx % 5)
    const qualifiedQty = checkQty - (idx % 3)
    const unqualifiedQty = checkQty - qualifiedQty
    return {
      id: idx + 1,
      inspectionName: `检验记录-${idx + 1}`,
      inspectionCode: `JY${(202500 + idx).toString()}`,
      orderName: `工单G${(8045 + idx).toString()}`,
      taskName: `任务${idx + 1}`,
      siteName: `站点${(idx % 4) + 1}`,
      processName: `工序${['一', '二', '三'][idx % 3]}`,
      productName: `新产品-0${(idx % 5) + 1}`,
      productCode: `CP0${(idx % 5) + 1}`,
      teamName: `班组${['一', '二', '三'][idx % 3]}`,
      taskOwner: ownerPool[idx % ownerPool.length] ?? ownerPool[0]!,
      reportUser: reporterPool[idx % reporterPool.length] ?? reporterPool[0]!,
      reportQty: plan,
      reportTime: `2025-11-${(idx % 9) + 18} 08:0${idx % 2}`,
      inspectionTime: `2025-11-${(idx % 9) + 18} 10:3${idx % 3}`,
      inspectionType:
        inspectionTypePool[idx % inspectionTypePool.length] ?? inspectionTypePool[0]!,
      inspectionDept: `质检部${(idx % 2) + 1}`,
      inspector: inspectors[idx % inspectors.length] ?? inspectors[0]!,
      checkQty,
      qualifiedQty,
      unqualifiedQty,
      qualifiedRate: `${((qualifiedQty / checkQty) * 100).toFixed(1)}%`,
      result: qualifiedQty === checkQty ? '合格' : '复检',
      status: statuses[idx % statuses.length] ?? statuses[0]!
    }
  })
}

onMounted(() => {
  fetchList()
})
</script>

<style scoped>
.quality-inspection-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 4px;
}

.breadcrumb-container {
  background: #fff;
  padding: 12px 20px;
  border-radius: 8px;
  box-shadow: 0 6px 16px rgba(64, 90, 182, 0.08);
}

.breadcrumb-item {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  color: #7c89a3;
}

.breadcrumb-item.active span {
  color: #2f54eb;
  font-weight: 600;
}

.breadcrumb-icon {
  color: #6c7fd8;
}

.filter-card,
.table-card {
  border-radius: 12px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.filter-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.toolbar {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.inspection-table {
  font-size: 13px;
}

.w-180 {
  width: 180px;
}

.more-btn {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.flex-end {
  display: flex;
  justify-content: flex-end;
}
</style>

